package com.xyrl.project.common.authentication;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xyrl.common.base.exception.OtherLoginException;
import com.xyrl.common.core.properties.XyrlProperties;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.project.common.base.vo.ResponseData;
import com.xyrl.project.common.util.SpringContextUtil;
import com.xyrl.project.common.util.XyrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {
    //放入head中的key 值
    @Value("${xyrl.headKey:token}")
    private String headKey;
    //是否开启权限校验
    @Value("${xyrl.shiro.isAuth:true}")
    private boolean isAuth;
    @Value("${xyrl.shiro.close.auth.default.user:mrbird}")
    private String defaultUser;
    @Value("${xyrl.shiro.close.auth.default.userType:system}")
    private String defaultUserType;

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        log.info("headKey=:{}", headKey);
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        XyrlProperties febsProperties = SpringContextUtil.getBean(XyrlProperties.class);
        //排除过滤项
        String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(febsProperties.getShiro().getAnonUrl(), StringPool.COMMA);
        boolean match = false;
        //判断量否有排除权限的url
        if (ObjectUtil.isNotEmpty(anonUrl)) {
            for (String u : anonUrl) {
                if (pathMatcher.match(u, httpServletRequest.getRequestURI())) {
                    match = true;
                }
            }
            if (match) {
                return true;
            }
        }
        if (isLoginAttempt(request, response)) {
            return executeLogin(request, response);
        }
        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        //不需要权限校验时直接返回
        if (!isAuth) {
            return true;
        }
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(headKey);
        log.debug("请求传入token:{}", token);
        return token != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(headKey);
        //不需要权限校验时 通过设置的默认用户生成token
        if (!isAuth && ObjectUtil.isEmpty(
                token)) {
            LoginInfo info = new LoginInfo(defaultUser, defaultUserType);
            token = JWTUtil.sign(info, defaultUser);
            token = XyrlUtil.encryptToken(token);
        }
        JWTToken jwtToken = new JWTToken(XyrlUtil.decryptToken(token));
        try {
            getSubject(request, response).login(jwtToken);
            return true;
        } catch (OtherLoginException e) {
            log.error(e.getMessage());
            throw new OtherLoginException(JSON.toJSONString(ResponseData.otherLogin(e.getMessage())));
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个 option请求，这里我们给 option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
        log.debug("Authentication required: sending 401 Authentication challenge response.");
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        final String message = "请在前端系统进行认证";
        try (PrintWriter out = httpResponse.getWriter()) {
            String responseJson = "{\"message\":\"" + message + "\",\"status\":401}";
            out.print(responseJson);
        } catch (IOException e) {
            log.error("sendChallenge error：", e);
        }
        return false;
    }
}
